<?php
namespace app\company\controller;

use app\company\model\Permissions;
use think\Request;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Db;
class Permission extends Base{

    public function _initialize()
    {
        parent::_initialize();
    }

    public function index(){
        $list = Permissions::getTree();
        $this->assign(compact("list"));
        return $this->fetch();
    }

    public function create(Request $request){
        if($request->isPost()){
            return $this->store($request);
        }
        $permissionList = Permissions::getTree();
        $this->assign(compact("permissionList"));
        return $this->fetch();
    }

    public function edit(Request $request){
        if($request->isPost()){
            return $this->store($request);
        }
        $params = [
            "id"    =>  input("route.id/d",0),
        ];
        $info = model("Permissions")->get($params["id"]);
        $where=[
            "id"    =>  ["neq",$info["id"]],
        ];
        $permissionList = Permissions::getTree($where);
        $this->assign(compact("permissionList","info"));
        return $this->fetch('create');
    }

    private function store(Request $request){
        $params = $request->only([
            "id","pid","title","icon","url","sort","status"
        ],"post");
        $permissionValidate =   model("Permission","validate");
        if(!$permissionValidate->scene("store")->check($params)){
            return $this->ajaxReturn(1,$permissionValidate->getError());
        }
        $params["url"] = ucfirst(strtolower($params["url"]));
        $obj = model("Permissions");
        $params["id"] && $obj->isUpdate(true);
        $obj->save($params);
        return $this->ajaxReturn(0,"", url("Permission/index"));
    }

    public function delete(){
        $params =   [
            "id"    =>  input("post.id/d",0),
        ];
        model("Permissions")->where("id",$params["id"])->delete();
        return $this->ajaxReturn();
    }

    /**
     * 全局参数设置
     */
    public function overall(){
        $info = db('com_config')->where('com_id', $this->com_id)->find();
        $info['record_people_num'] = unserialize($info['record_people_num']);
        $info['record_event_num'] = unserialize($info['record_event_num']);
        $this->assign('info', $info);
        return $this->fetch();
    }
    public function overall_edit(){
        $param = input();
        $param['record_people_num'] = []; //奖扣人次
        $param['record_event_num'] = []; //奖扣事件数
        //遍历奖扣人次
        foreach($param['people_sum'] as $k=>$v){
            if($v && $v>=0 && $param['prize_integral'][$k] && $param['prize_integral'][$k]>=0){
                $param['record_people_num'][] = ['people_sum'=>$v, 'prize_integral'=>$param['prize_integral'][$k]];
            }
        }
        //遍历奖扣事件数
        foreach($param['prize_sum'] as $k=>$v){
            if($v && $v>=0 && $param['event_prize_integral'][$k] && $param['event_prize_integral'][$k]>=0){
                $param['record_event_num'][] = ['prize_sum'=>$v, 'event_prize_integral'=>$param['event_prize_integral'][$k]];
            }
        }
        $param['record_people_num'] = serialize($param['record_people_num']);
        $param['record_event_num'] = serialize($param['record_event_num']);
        if(isset($param['is_open_shop'])){
            $param['is_open_shop'] = 1;
        }else{
            $param['is_open_shop'] = 0;
        }
        if(isset($param['is_open_ranking'])){
            $param['is_open_ranking'] = 1;
        }else{
            $param['is_open_ranking'] = 0;
        }
        //删除表不存在的参数
        unset($param['people_sum'], $param['prize_integral'], $param['prize_sum'], $param['event_prize_integral']);
        //负数转为0
        foreach($param as $k=>$v){
            if(is_numeric($v) && $v<0){
                $param[$k] = 0;
            }
        }
        foreach($param as $k=>$v){
            db('com_config')->where('com_id', $this->com_id)->update([$k=>$v]);
        }
        return $this->ajaxReturn(0, '成功');
    }

    /**
     * 奖扣权限
     */
    public function prize_buckle(){
        $where = [
            'cpb.com_id'=>$this->com_id
        ];
        $list = db('com_prize_buckle')->alias('cpb')
            ->join('com_prize_buckle_relation_users cpbr', 'cpbr.prize_buckle_id=cpb.id', 'LEFT')
            ->field('cpb.id, cpb.name, cpb.integral_a, cpb.integral_b, count(cpbr.id) as cpbr_num')
            ->group('cpb.id')
            ->where($where)->order('cpb.id desc')->paginate('',false,page_param());
        $this->assign('list', $list);
        return $this->fetch();
    }

    public function prize_add(){
        if(request()->isPost()){
            return $this->prize_store();
        }
        return $this->fetch('prize_edit');
    }

    public function prize_edit(){
        if(request()->isPost()){
            return $this->prize_store();
        }
        if(input('id')){
            $where = ['id'=>input('id'), 'com_id'=>$this->com_id];
            $info = db('com_prize_buckle')->where($where)->find();
            $this->assign('info', $info);
        }
        return $this->fetch();
    }

    public function prize_del(){
        $id = input('id');
        $relation_info = db('com_prize_buckle_relation_users')->where('prize_buckle_id', $id)->find();
        if($relation_info){
            return $this->ajaxReturn(1, '删除失败 已有人员关联该权限');
        }
        db('com_prize_buckle')->where('id', $id)->delete();
        return $this->ajaxReturn(0,"成功", url(CONTROLLER_NAME.'/prize_buckle'));
    }

    public function prize_store(){
        $params = input();
        $check = $this->validate(
            $params,
            ['name|名称'=>'require|max:30']
        );
        if(true !== $check){
            return $this->ajaxReturn(1, $check);
        }
        $where = [];
        $where['com_id'] = $this->com_id;
        $where['name'] = $params['name'];
        if($params['id']){
            //判断是否重名
            $where['id'] = ['neq',$params['id']];
            $list = M('com_prize_buckle')->where($where)->find();
            if(!empty($list)){
                return $this->ajaxReturn(1,'该名称已存在');
            }
            $where = ['id'=>$params['id'], 'com_id'=>$this->com_id];
            db('com_prize_buckle')->where($where)->update($params);
        }else{
            $list = M('com_prize_buckle')->where($where)->find();
            if(!empty($list)){
                return $this->ajaxReturn(1,'该名称已存在');
            }
            $params['com_id'] = $this->com_id;
            db('com_prize_buckle')->insert($params);
        }
        return $this->ajaxReturn(0,"成功", url(CONTROLLER_NAME.'/prize_buckle'));
    }
    //奖扣权限人员列表
    public function prize_user(){
        $id = I('id',0);
        $list = M('com_prize_buckle_relation_users a')
            ->join('users b','b.id = a.user_id','left')
            ->join('com_department c','c.id = b.department_id','left')
            ->where('a.prize_buckle_id',$id)
            ->field('a.id,b.avatar,b.name,c.name department_name')
            ->paginate('',false,page_param());
        $this->assign('list',$list);
        $this->assign('id',$id);
        return $this->fetch();
    }
    //新增权限人员
    public function user_edit(Request $request){
        if($request->isPost()){
            return $this->user_store($request);
        }
        $id = I('id',0);
        $com_id = $this->com_id;
        $ids = M('com_prize_buckle_relation_users')->where('com_id',$com_id)->column('user_id');
        $where['id'] = ['not in',$ids];
        $where['com_id'] = $com_id;
        $where['type'] = 1;//未冻结
        $where['status'] = 1;//正常用户
        $list = M('users')->where($where)->select();
        $this->assign('user_list',$list);
//        var_dump($list);die;
        $this->assign('id',$id);
        return $this->fetch();
    }
    //新增权限人员提交
    public function user_store(){
       $id = I('id',0);
       $user_ids = I('user_id/a',[]);
        if(empty($id)){
            return $this->ajaxReturn(1,'权限id不能为空');
        }
        if(empty($user_ids)){
            return $this->ajaxReturn(1,'用户id不能为空');
        }
        $where= [];
        $where['com_id'] = $this->com_id;
//        $where['prize_buckle_id'] = $id;
        $where['user_id'] = ['in',$user_ids];

        DB::startTrans();
        try{
            //删除存在的用户
            M('com_prize_buckle_relation_users')->where($where)->delete();
            //新增权限用户
            $data_add = [];
            foreach ($user_ids as $value){
                $data_add[] = [
                    'com_id'=>$this->com_id,
                    'user_id'=>$value,
                    'prize_buckle_id'=>$id,
                ];
            }
            M('com_prize_buckle_relation_users')->insertAll($data_add);
            DB::commit();
            return $this->ajaxReturn(0,"成功");
        }catch (\Exception $e){
            DB::rollback();
            return $this->ajaxReturn(1,$e->getMessage());
        }
    }
    //删除
    public function user_del(){
        $params = input();
        $ids = explode(',', $params['id']);
        db('com_prize_buckle_relation_users')->where('id', 'in', $ids)->delete();
        return $this->ajaxReturn(0, '成功');
    }
    //导入
    public function prize_buckle_import()
    {
        if($_FILES['file']['error'] != 0){
            return $this->ajaxReturn(1, "文件上传有误");
        }
        //文件是否大于2M
        if($_FILES['file']['size'] > 102400*5){
            return $this->ajaxReturn(1, "文件最大5M");
        }
        $r = action('file/controller_up');
        if($r['err'] != 0){
            return $this->ajaxReturn(1, "文件保存出错");
        }
        $path = ROOT_PATH.'public'.$r['data']['saveName'];
        $type = 'Xlsx';//设置为Xls代表支持2003或以下版本，Xlsx代表2007版
        $xlsReader = IOFactory::createReader($type);
        $xlsReader->setReadDataOnly(true);
        $Sheets = $xlsReader->load($path);
        $dataArray = $Sheets->getSheet(0)->toArray();
        unlink($path);
        unset($dataArray[0]);       //删除第一行，从第二行开始读取
        unset($dataArray[1]);       //删除第二行，从第三行开始读取
        //企业所有的权限
        $prize_buckle_names = M('com_prize_buckle')->where(['com_id'=>$this->com_id])->column('name');
        $prize_buckle_ids = M('com_prize_buckle')->where(['com_id'=>$this->com_id])->column('id','name');
        $job_number_ids = M('users')->where(['com_id'=>$this->com_id])->column('job_number');
        $user_ids = M('users')->where(['com_id'=>$this->com_id])->column('id','job_number');
        $com_prize_buckle_relation_users = M('com_prize_buckle_relation_users')
            ->where(['com_id'=>$this->com_id])
            ->column('user_id');
        $com_prize_buckle_relation_users_ids= M('com_prize_buckle_relation_users')
            ->where(['com_id'=>$this->com_id])
            ->column('id','user_id');
//        var_dump($user_ids);die;
        $err_msg = '';
        $data = [];
        $data_add = [];
//        var_dump($dataArray);die;
        foreach ($dataArray as $key=>$row){
            $index = $key + 1;
            if(!empty($row[0])) {
                //字段验证
                if (empty($row[0])||empty($row[1])||empty($row[2])){
                    $err_msg .= '第'.$index.'行数据缺失';
                }
                //查询权限名称是否存在
                if(!in_array($row[0],$prize_buckle_names)){
                    $err_msg .= '第'.$index.'行数据权限名称不存在';
                }
                //查询用户是否存在
                if(!in_array($row[1],$job_number_ids)){
                    $err_msg .= '第'.$index.'行数据用户不存在';
                }
                $id = $user_ids[$row[1]]??0;
                $prize_buckle_id = $prize_buckle_ids[$row[0]]??0;
                if(in_array($id,$com_prize_buckle_relation_users)){
                    $relation_id = $com_prize_buckle_relation_users_ids[$id]??0;
                    $data[] = [
                        'id'=>$relation_id,
                        'prize_buckle_id'=>$prize_buckle_id
                    ];
                }else{
                    $data_add[] = [
                        'com_id'=>$this->com_id,
                        'prize_buckle_id'=>$prize_buckle_id,
                        'user_id'=>$id,
                    ];
                }

            }
        }
        if(!empty($err_msg)){
            return $this->ajaxReturn(1,$err_msg);
        }else{
            DB::startTrans();
            try{
                if(!empty($data)){
                    dbSaveAll($data, 'com_prize_buckle_relation_users', 'id');
                }
                if(!empty($data_add)){
                    M('com_prize_buckle_relation_users')->insertAll($data_add);
                }
                DB::commit();
                return $this->ajaxReturn(0,'导入成功');
            }catch (\Exception $e){
                DB::rollback();
                return $this->ajaxReturn(1,$e->getMessage());
            }
        }
    }

}
